package com.leonzx.base.config.interceptor;

import com.google.gson.Gson;
import com.leonzx.base.service.RedisService;
import com.leonzx.base.utils.HttpUtils;
import com.leonzx.base.utils.RedisConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author:梁亮
 * @Description:
 * @Date: 2018/7/30 14:17
 */
@Component
public class AppTokenInterceptor extends HandlerInterceptorAdapter {

    private final Logger logger = LoggerFactory.getLogger(AppTokenInterceptor.class);

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestPath = request.getRequestURI();
        logger.info("requestIp: " + HttpUtils.getIpAddress(request));
        logger.info("requestPath: " + requestPath);
        if (requestPath.contains("/v2/api-docs") || requestPath.contains("/swagger") || requestPath.contains("/configuration/ui")) {
            return true;
        }

        if (requestPath.contains("/login")) {
            return true;
        }

        if (requestPath.contains("/error")) {
            return true;
        }

        String token = request.getParameter("token");
        logger.info("token: " + token);
        if (StringUtils.isEmpty(token)) {
            authFailed(request, response);
            return false;
        }

        String userString = redisService.getValue(RedisConstants.USER_TOKEN + token);
        if (StringUtils.isEmpty(userString)) {
            authFailed(request, response);
            return false;
        }
        return true;
    }

    public void authFailed(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> result = new HashMap<>();
        result.put("data", null);
        result.put("code", "9");
        result.put("msg", "TOKEN认证失败");
        Gson gson = new Gson();
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(gson.toJson(result));
    }
}
